package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.dao.mapper.UserMapper;
import com.chen.dao.pojo.User;
import com.chen.service.UserService;
import com.chen.vo.Result;
import com.chen.vo.param.UserParam;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:chenao
 * @DATE:2022/3/6 14:35
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result saveUser(UserParam param) {
        User user = new User();
        user.setGender(param.getGender());
        user.setNickName(param.getNickName());
        user.setOpenId(param.getOpenId());
        user.setAddress(param.getProvince()+param.getCity());
        user.setAvatarUrl(param.getAvatarUrl());
        if (isExist(param.getOpenId())){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getOpenId,user.getOpenId());
            userMapper.update(user,queryWrapper);
        }else {
            userMapper.insert(user);
        }
        //登录后将更新后的用户信息返回
        User userInfo = queryUserByOpenId(param.getOpenId());
        return Result.success(userInfo);
    }

    @Override
    public User queryUserByOpenId(String openId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenId,openId);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User queryUserById(String id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,id);
        return userMapper.selectOne(queryWrapper);
    }

    public Boolean isExist(String openId){
        User user = queryUserByOpenId(openId);
        return user==null?false:true;
    }

    public Result update(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenId,user.getOpenId());
        userMapper.update(user,queryWrapper);
        return Result.success("ok");
    }
}
